package com.tianruan.psychological.moduls.auth.security;

import com.alibaba.fastjson.JSONObject;
import com.tianruan.psychological.common.response.VResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: Dong
 * @Email: dong980514280@gmail.com
 * @Create: 2019-11-25 17:01
 * @PS
 */
@Configuration
public class CustomerAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        //设置response状态码，返回错误信息等

        int status = HttpServletResponse.SC_UNAUTHORIZED;
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(status);
        PrintWriter out = response.getWriter();
        if (e instanceof InsufficientAuthenticationException) {
            out.write(JSONObject.toJSONString(VResponse.error(status, "令牌为空或失效")));
        } else {
            out.write(JSONObject.toJSONString(VResponse.error(status, "未登录")));
        }
        out.flush();
        out.close();
    }

}